package com.sxbbc.common.core.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.sxbbc.common.basics.service.redis.RedisUtilsService;
import com.sxbbc.common.core.dto.jz.FarmLogisticsOrderOutVo;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.*;
import com.sxbbc.common.core.mapper.jz.ChickenCouponMapper;
import com.sxbbc.common.core.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.enums.LoginChannelEnums;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.mapper.jz.OrderMainMapper;
import com.sxbbc.common.core.utils.BasePage;

/**
 * <p>
 * 订单主表信息 服务实现类
 * </p>
 *
 * @author xiaoky
 * @since 2019-05-09
 */
@Service
public class OrderMainServiceImpl extends ServiceImpl<OrderMainMapper, OrderMain> implements IOrderMainService {
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private OrderMainMapper orderMainMapper;
    @Autowired
    private IOrderExpDetailService orderExpDetailService;
    @Autowired
    private ICCustomerService customerService;
    @Autowired
    private IWWarehouseService iwWarehouseService;
    @Autowired
    private IOrderRefundLogService orderRefundLogService;
    @Autowired
    private IOrderConfigGroupService orderConfigGroupService;
    @Autowired
    private IPushService pushService;
    @Autowired
    private RedisUtilsService redisUtilsService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private IAccountChangeService accountChangeService;
    @Autowired
    private IInfoParamService infoParamService;
    @Autowired
    private ChickenCouponMapper chickenCouponMapper;

    @Override
    public OrderMain getByOrderCode(String orderCode) {
        QueryWrapper<OrderMain> orderWrapper = new QueryWrapper<OrderMain>();
        orderWrapper.eq("order_code", orderCode);
        OrderMain order = super.getOne(orderWrapper);
        return order;
    }

    @Override
    public Map<String, Integer> getOfflineOrderNum(OrderMain order) {
        // 封装Map
        Map<String, Integer> map = new HashMap<>();
        // 待付款数量
        order.setOrderStatus(OfflineOrderStatusEnums.COMFIRE.getId());
        int waitPayNum = orderMainMapper.countOrderNum(order);
        map.put("waitPayNum", waitPayNum);
        // 待核销数量
        order.setOrderStatus(OfflineOrderStatusEnums.WAIT_USED.getId());
        int waitSendNum = orderMainMapper.countOrderNum(order);
        map.put("waitUseNum", waitSendNum);
        // 已完成数量
        order.setOrderStatus(OfflineOrderStatusEnums.COMPLETE.getId());
        int waitReceiveNum = orderMainMapper.countOrderNum(order);
        map.put("overNum", waitReceiveNum);
        return map;
    }

    @Override
    public Map<String, Integer> getOrderNum(OrderMain order) {
        // 封装Map
        Map<String, Integer> map = new HashMap<>();
        // 待付款数量
        order.setOrderStatus(OrderStatusEnums.COMFIRE.getId());
        int waitPayNum = orderMainMapper.countOrderNum(order);
        map.put("waitPayNum", waitPayNum);
        // 待发货数量
        order.setOrderStatus(OrderStatusEnums.NEED_SEND.getId());
        int waitSendNum = orderMainMapper.countOrderNum(order);
        map.put("waitSendNum", waitSendNum);
        // 待收货数量
        order.setOrderStatus(OrderStatusEnums.HAS_SEND.getId());
        int waitReceiveNum = orderMainMapper.countOrderNum(order);
        map.put("waitReceiveNum", waitReceiveNum);
        // 待评价数量
        order.setOrderStatus(OrderStatusEnums.RECEIVED.getId());
        int waitCommNum = orderMainMapper.countOrderNum(order);
        map.put("waitCommNum", waitCommNum);
        // 退款\售后
        QueryWrapper<OrderRefundLog> refundWrapper = new QueryWrapper<OrderRefundLog>();
        refundWrapper.eq("cid", order.getCid()).eq("status", StaticUtils.STATUS_APPLY);
        int refundNum = orderRefundLogService.count(refundWrapper);
        map.put("refundNum", refundNum);
        return map;
    }

    @Override
    public IPage<OrderMain> queryOrder(BasePage<OrderMain> page, OrderMain orderMain) {
        if (StringUtils.isNotBlank(orderMain.getQueryTime())) {
            String[] times = orderMain.getQueryTime().split("~");
            orderMain.setStart(times[0]);
            orderMain.setEnd(times[1]);
        }
        IPage<OrderMain> pageInfo = orderMainMapper.queryOrder(page, orderMain);

        //IPage<OrderMain> pageInfo = orderMainMapper.queryOrderList(page, orderMain);
        for (OrderMain order : pageInfo.getRecords()) {
            // 订单类型
            String orderTypeName = OrderTypeEnums.getName(order.getOrderType());
            order.setOrderTypeName(orderTypeName);
            // 处理订单状态
            handleOrderStatusName(order);
            // 支付方式
            order.setPayTypeName(PayTypeEnums.getName(order.getPayType()));
            // 订单来源
            order.setOrderFromChannel(LoginChannelEnums.getName(order.getFromChannel()));
            // 订单详情
            List<OrderDetail> details = orderDetailService.listByOrderCode(order.getOrderCode());
            order.setDetails(details);
            // 物流信息
            if (order.getOrderStatus() != null && order.getOrderStatus() >= OrderStatusEnums.NEED_SEND.getId()) {
                QueryWrapper<OrderExpDetail> wrapper = new QueryWrapper<>();
                wrapper.eq("order_code", order.getOrderCode());
                List<OrderExpDetail> list = orderExpDetailService.list(wrapper);
                if (list != null && list.size() > 0) {
                    order.setExpDetail(list.get(0));
                }

            }
            //仓库
            if (order.getWid() != null) {
                WWarehouse wWarehouse = iwWarehouseService.getById(order.getWid());
                order.setWarehouseName(wWarehouse.getName());
            }
        }
        return page;
    }

    /**
     * 处理订单状态名称
     *
     * @param order
     * @author xiaoky
     */
    private void handleOrderStatusName(OrderMain order) {
        String statusPrefix = "";
        // 订单状态名称后缀
        String statusSuffix = OrderStatusEnums.getName(order.getOrderStatus());
        // 积分订单处理——判断先用payType为积分
        if (CalcuUtils.getInstance().isEquals(order.getPayType(), PayTypeEnums.PAY_POINT.getId())) {
            statusPrefix = "「积分」";
        }
        // 订单状态
        order.setOrderStatusName(statusPrefix + statusSuffix);
    }

    @Override
    public OrderMain getOrderDetailById(Integer orderId) {
        OrderMain order = super.getById(orderId);
        if (order != null) {
            // 订单类型
            order.setOrderTypeName(OrderTypeEnums.getName(order.getOrderType()));
            // 支付方式
            order.setPayTypeName(PayTypeEnums.getName(order.getPayType()));
            // 订单状态
            handleOrderStatusName(order);
            // 订单来源
            order.setOrderFromChannel(LoginChannelEnums.getName(order.getFromChannel()));
            // 订单详情
            List<OrderDetail> details = orderDetailService.listByOrderCode(order.getOrderCode());
            order.setDetails(details);
            CCustomer customer = customerService.getById(order.getCid());
            if (customer != null) {
                order.setPhone(customer.getPhone());
            }
            // 物流信息
            /*OrderExpDetail expDetail = orderExpDetailService.getByOrderCode(order.getOrderCode());
            if (expDetail != null) {
//				// 最新的物流数据
//				String expMsg = orderExpDetailService.getLiveExpData(expDetail.getId());
//				// 获取最近的物流时间和物流事件
//				getAcceptExp(order, expMsg);
                expDetail.setReceivedTypeName(ReceivedTypeEnums.getName(expDetail.getReceivedType()));
                order.setExpDetail(expDetail);
            }*/
//			// 如果是团购订单(查询团购人员信息)
//			if (CalcuUtils.getInstance().isEquals(order.getOrderType(), OrderTypeEnums.GROUPS.getId())) {
//				QueryWrapper<OrderConfigGroup> wrapper = new QueryWrapper<OrderConfigGroup>();
//				wrapper.eq("order_code", order.getOrderCode());
//				OrderConfigGroup configGroup = orderConfigGroupMapper.selectOne(wrapper);
//				// 团购用户信息
//				List<GroupVo> msgList = orderConfigGroupMapper.queryGroupByGroupCode(configGroup.getGroupCode());
//			}
        }
        return order;
    }

    @Override
    public RestResponse handleSendGood(Integer orderId, Integer receivedType, String expCode, String expName,
                                       String expNo) {
        OrderMain order = super.getById(orderId);
        if (order == null) {
            return GetRest.getFail("订单不存在");
        }
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        if (!calcuUtils.isEquals(OrderStatusEnums.NEED_SEND.getId(), order.getOrderStatus())) {
            throw new ThrowJsonException("订单[" + order.getOrderCode() + "]不是待发货状态");
        }

        if (receivedType == null) {
            return GetRest.getFail("请选择发货方式");
        }

        OrderExpDetail logisticsDetail = orderExpDetailService.getByOrderCode(order.getOrderCode());
        // 处理订单数据
        // 物流发货
        if (calcuUtils.isEquals(ReceivedTypeEnums.EXP.getId(), receivedType)) {
            if (StringUtils.isBlank(expCode)) {
                return GetRest.getFail("请选择物流公司");
            }
            if (StringUtils.isBlank(expNo)) {
                return GetRest.getFail("请填写快递单号");
            }
            order.setOrderStatus(OrderStatusEnums.HAS_SEND.getId()); // 改为发货状态
            // 物流信息
            logisticsDetail.setExpCode(expCode);
            logisticsDetail.setExpName(expName);
            logisticsDetail.setExpNo(expNo);
        } else {
            // 如果是虚拟发货和自提 则直接状态为已收货
            order.setOrderStatus(OrderStatusEnums.RECEIVED.getId());
            order.setReceivedTime(new Date());
        }
        order.setSendTime(new Date());
        boolean result = super.updateById(order);
        if (result) {
            // 处理物流数据
            logisticsDetail.setSign(StaticUtils.STATUS_NO);
            logisticsDetail.setReceivedType(receivedType);
            logisticsDetail.setSendTime(new Date());
            result = orderExpDetailService.updateById(logisticsDetail);
            if (!result) {
                throw new ThrowJsonException("发货失败");
            }
            return GetRest.getSuccess("发货成功");
        }
        return GetRest.getFail("发货失败");
    }

    @Override
    public RestResponse handleOrderDeliver(OrderExpDetail expDetail) {
        //自营店铺 检查order_exp_detail的发货状态
        //如果都已发货，更新order_main的状态
        //否则更新当前ID的状态
        //非自营店铺 直接发货
        boolean save = false;
        CalcuUtils calUtil = CalcuUtils.getInstance();
        //订单
        OrderMain order = super.getById(expDetail.getOrderId());
        //订单发货单
        OrderExpDetail orderExpDetail = orderExpDetailService.getById(expDetail.getId());
        if (calUtil.isEquals(order.getBType(), BusinessTypeEnums.OWN_BUSINESS.getId())) {
            //自营店时检查order_exp_detail表中所有发货状态
            QueryWrapper<OrderExpDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("order_code", order.getOrderCode()).eq("status", StaticUtils.STATUS_NO).ne("id", expDetail.getId());
            int count = orderExpDetailService.count(wrapper);
            if (count < 1) {
                //订单状态改为发货
                order.setOrderStatus(OrderStatusEnums.HAS_SEND.getId());
            }
        } else {
            //非自营 不用检查order_exp_detail的发货状态，直接更新
            order.setOrderStatus(OrderStatusEnums.HAS_SEND.getId());
        }
        if (calUtil.isEquals(expDetail.getReceivedType(), ReceivedTypeEnums.EXP.getId())) {
            //物流信息表
            orderExpDetail.setExpCode(expDetail.getExpCode());
            orderExpDetail.setExpName(expDetail.getExpName());
            orderExpDetail.setExpNo(expDetail.getExpNo());
        } else {
            QueryWrapper<OrderExpDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("order_code", order.getOrderCode())
                    .eq("status", StaticUtils.STATUS_YES).eq("received_type", ReceivedTypeEnums.EXP.getId());
            int count = orderExpDetailService.count(wrapper);
            if (count == 0) {
                //虚拟发货及自提 直接收货
                order.setOrderStatus(OrderStatusEnums.RECEIVED.getId());
                order.setReceivedTime(new Date());
            }
        }
        order.setSendTime(new Date());
        save = super.updateById(order);
        if (!save) {
            throw new ThrowJsonException("发货失败");
        }
        orderExpDetail.setSign(StaticUtils.STATUS_NO);
        orderExpDetail.setReceivedType(expDetail.getReceivedType());
        orderExpDetail.setSendTime(new Date());
        orderExpDetail.setStatus(StaticUtils.STATUS_YES);
        save = orderExpDetailService.updateById(orderExpDetail);
        if (!save) {
            throw new ThrowJsonException("发货失败");
        }

        //发货成功，将运费结算给商家，需要扣除12个点的平台费
        BigDecimal expMoney = order.getExpMoney();
        if (expMoney.compareTo(BigDecimal.ZERO) > 0) {
            BigDecimal businessScale = calUtil.getValueByClass(BigDecimal.class, infoParamService.getValueByCode(ParamEnums.BUSINESS_SCALE));
            //平台收益（商家让利）
            BigDecimal scale = calUtil.mul(expMoney, businessScale, 2);
            BigDecimal realMoney = calUtil.sub(expMoney, scale, 2);
            //以下代码注释是因为去掉了对应的枚举类，实际应该存在
            String expmoneyDetail = accountChangeService.insertBMoneyDetail(order.getBid(), HandleTypeEnums.FREIGHT.getId(), StaticUtils.PAY_IN,
                    order.getPayCode(), realMoney, HandleTypeEnums.getName(HandleTypeEnums.FREIGHT.getId()), order.getCid());
            if (!StringUtils.isEmpty(expmoneyDetail)) {
                throw new ThrowJsonException("运费结算失败：" + expmoneyDetail);
            }
        }



        //推送订单发货通知
//        String token = redisUtilsService.getKey(order.getCid() + "_token");
//        PushVo pushVo = new PushVo(token, MsgUtils.JPUSH_0002, PushTypeEnums.ORDER_NOTICE.getId(),
//                order.getOrderCode(), new String[]{order.getOrderCode(), expDetail.getExpNo()}, order.getCid());
//        pushService.pushMessageById(pushVo);
        return GetRest.getSuccess("发货成功");
    }

    @Override
    public RestResponse handleUpdateSendCode(OrderExpDetail expDetail) {
        boolean save = false;
        CalcuUtils calUtil = CalcuUtils.getInstance();
        //订单发货单
        OrderExpDetail orderExpDetail = orderExpDetailService.getById(expDetail.getId());
        if (calUtil.isEquals(orderExpDetail.getReceivedType(), ReceivedTypeEnums.EXP.getId())) {
            //物流信息表
            orderExpDetail.setExpCode(expDetail.getExpCode());
            orderExpDetail.setExpName(expDetail.getExpName());
            orderExpDetail.setExpNo(expDetail.getExpNo());
        } else {
            return GetRest.getFail("发货单非物流发货");
        }
        orderExpDetail.setSign(StaticUtils.STATUS_NO);
        orderExpDetail.setStatus(StaticUtils.STATUS_YES);
        save = orderExpDetailService.updateById(orderExpDetail);
        if (!save) {
            throw new ThrowJsonException("修改失败");
        }
        return GetRest.getSuccess("修改成功");
    }

    @Override
    public RestResponse editOrderReceive(OrderExpDetail expDetail) {
        OrderMain order = this.getByOrderCode(expDetail.getOrderCode());
        if (order == null) {
            return GetRest.getFail("修改失败，订单数据有误");
        }
        CalcuUtils caUtils = CalcuUtils.getInstance();
        if (!(caUtils.isEquals(order.getOrderStatus(), OrderStatusEnums.NEED_SEND.getId())
                || caUtils.isEquals(order.getOrderStatus(), OrderStatusEnums.HAS_SEND.getId()))) {
            return GetRest.getFail("当前订单状态不可修改");
        }
        QueryWrapper<OrderExpDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("order_code", expDetail.getOrderCode());
        List<OrderExpDetail> expList = orderExpDetailService.list(wrapper);
        if (CollectionUtils.isEmpty(expList)) {
            throw new ThrowJsonException("修改失败");
        }
        for (OrderExpDetail detail : expList) {
            String nameExt = addressService.getAddrName(expDetail.getProId(), expDetail.getCityId(), expDetail.getAreaId());
            detail.setAddrids(expDetail.getProId() + "," + expDetail.getCityId() + "," + expDetail.getAreaId());
            detail.setAddressDetail(expDetail.getAddressDetail());
            detail.setAddrPrefix(nameExt);
            boolean result = orderExpDetailService.updateById(detail);
            if (!result) {
                throw new ThrowJsonException("修改失败");
            }
        }
        return GetRest.getSuccess("修改成功");
    }

    @Override
    public IPage<OrderMain> queryBusinessOrderRefundDetail(BasePage<OrderMain> page, OrderMain orderMain, Integer timeDays) {
        IPage<OrderMain> pageInfo = orderMainMapper.queryBusinessOrderRefundDetail(page, orderMain, timeDays);
        for (OrderMain order : pageInfo.getRecords()) {
            // 订单类型
            String orderTypeName = OrderTypeEnums.getName(order.getOrderType());
            order.setOrderTypeName(orderTypeName);
            // 处理订单状态
            handleOrderStatusName(order);
            // 支付方式
            order.setPayTypeName(PayTypeEnums.getName(order.getPayType()));
            // 订单来源
            order.setOrderFromChannel(LoginChannelEnums.getName(order.getFromChannel()));
            // 订单详情
            List<OrderDetail> details = orderDetailService.listByOrderCode(order.getOrderCode());
            order.setDetails(details);
            // 物流信息
            if (order.getOrderStatus() != null && order.getOrderStatus() >= OrderStatusEnums.NEED_SEND.getId()) {
                QueryWrapper<OrderExpDetail> wrapper = new QueryWrapper<>();
                wrapper.eq("order_code", order.getOrderCode());
                List<OrderExpDetail> list = orderExpDetailService.list(wrapper);
                if (list != null && list.size() > 0) {
                    order.setExpDetail(list.get(0));
                }
            }
            //仓库
            if (order.getWid() != null) {
                WWarehouse wWarehouse = iwWarehouseService.getById(order.getWid());
                order.setWarehouseName(wWarehouse.getName());
            }
        }
        return page;
    }

    @Override
    public IPage<FarmLogisticsOrderOutVo> selectChickenLogisticsOrderList(BasePage<OrderMain> page, OrderMain orderMain) {
        if (StringUtils.isNotBlank(orderMain.getQueryTime())) {
            String[] times = orderMain.getQueryTime().split("~");
            orderMain.setStart(times[0]);
            orderMain.setEnd(times[1]);
        }
        orderMain.setOrderType(OrderTypeEnums.LOGISTICS.getId());
        IPage<OrderMain> pageInfo = orderMainMapper.queryOrder(page, orderMain);

        BasePage<FarmLogisticsOrderOutVo> voBasePage = new BasePage<>();
        ArrayList<FarmLogisticsOrderOutVo> outVos = new ArrayList<>();
        for (OrderMain order : pageInfo.getRecords()) {
            // 订单类型
            String orderTypeName = OrderTypeEnums.getName(order.getOrderType());
            order.setOrderTypeName(orderTypeName);
            // 处理订单状态
            handleOrderStatusName(order);
            // 支付方式
            order.setPayTypeName(PayTypeEnums.getName(order.getPayType()));
            // 订单来源
            order.setOrderFromChannel(LoginChannelEnums.getName(order.getFromChannel()));
            // 订单详情
            //List<OrderDetail> details = orderDetailService.listByOrderCode(order.getOrderCode());
            //order.setDetails(details);

            QueryWrapper<ChickenCoupon> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", order.getCouponId());
            ChickenCoupon chickenCoupon = chickenCouponMapper.selectOne(queryWrapper);
            FarmLogisticsOrderOutVo outVo = new FarmLogisticsOrderOutVo();
            BeanUtils.copyProperties(order, outVo);
            outVo.setCouponName(chickenCoupon.getTitle());
            outVos.add(outVo);
            voBasePage.setRecords(outVos);
            voBasePage.setCurrent(page.getCurrent());
            // 物流信息
//            if (order.getOrderStatus() != null && order.getOrderStatus() >= OrderStatusEnums.NEED_SEND.getId()) {
//                QueryWrapper<OrderExpDetail> wrapper = new QueryWrapper<>();
//                wrapper.eq("order_code", order.getOrderCode());
//                List<OrderExpDetail> list = orderExpDetailService.list(wrapper);
//                if (list != null && list.size() > 0) {
//                    order.setExpDetail(list.get(0));
//                }
//
//            }
        }
        return voBasePage;
    }

}
